package com.jhws.business.car.bo;

import com.alibaba.fastjson.JSON;
import com.jhws.business.car.service.CarInfoService;
import com.jhws.business.car.service.ParkingLotService;
import com.jhws.business.customer.bo.PayCustomerSecret;
import com.jhws.business.customer.service.PayCustService;
import com.jhws.common.pay.bo.IOrderPayModule;
import com.jhws.common.pay.bo.Order;
import com.jhws.common.pay.bo.PayModuleInfo;
import com.jhws.common.pay.service.OrderService;
import com.jhws.core.mns.service.IMNSService;
import com.jhws.util.DateUtil;
import com.jhws.util.LogHelper;
import com.jhws.util.StringUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

/* 停车缴费月卡订单处理模块 */
@Component
public class CarOrderPayModule implements IOrderPayModule {
    public final static String PAY_MODULE = "CAR"; //支付模块名
    public final static String ORDER_CAR_MONTH = "CAR_MONTH";
    public final static String ORDER_CAR_LANE = "CAR_LANE"; //车道支付
    public final static String ORDER_CAR_ORDERED = "CAR_ORDERED"; //预支付
    public final static String ORDER_CAR_TEMP = "CAR_TEMP";

    public final static String[] name = {PAY_MODULE, ORDER_CAR_MONTH, ORDER_CAR_LANE, ORDER_CAR_ORDERED, ORDER_CAR_TEMP};

    private final String[] desc = {"停车缴费", "车辆月卡缴费", "车道支付", "车辆预支付", "车辆临时支付"};

    @Resource
    private OrderService orderService;
    @Resource
    private CarInfoService carInfoService;
    @Resource
    private ParkingLotService parkingLotService;
    @Resource
    private IMNSService mnsService;
    @Resource
    private PayCustService payCustService;

    @Resource
    private RedisTemplate stringTemplate;

    @Override
    public String[] getModuleName() {
        return name;
    }

    @Override
    public String getPayModuleName() {
        return PAY_MODULE;
    }

    @Override
    public String[] getModuleDesc() {
        return desc;
    }

    @Override
    public void handle(Order order) throws Exception {
        if (order.getOrderType().equals(ORDER_CAR_MONTH)) {
            LogHelper.d("car month Pay by " + order.getPayType());
            CarPrivateInfo carPrivateInfo = JSON.parseObject(order.getDetail(), CarPrivateInfo.class);
            List<CarInfo> carInfos = carInfoService.queryCarInfoByWhere(" where park_id ='" + order.getAttach2() + "' and plate_number = '" + order.getAttach() + "'");
            CarInfo carInfo = carInfos != null && carInfos.size() > 0 ? carInfos.get(0) : null;
            if (carInfo == null) {
                carInfo = new CarInfo();
            }
            carInfo.setOwnerCode(order.getOwnerCode());
            carInfo.setParkId(order.getAttach2());
            carInfo.setPlateNumber(order.getAttach());
            carInfo.setCardType(CarConstant.CAR_PAYMENT_TYPE_CARD);
            carInfo.seteEndTime(DateUtil.stringDate(carPrivateInfo.getRenewExpirationTime(), DateUtil.DATE_FORMAT));
            if (carInfo.geteStartTime() == null) {
                carInfo.seteStartTime(new Date());
            }
            carInfoService.saveCarInfo(carInfo);
            //推送到队列
            CarMNSMessage mnsMessage = new CarMNSMessage();
            Map<String, Object> map = new HashMap<>();
            map.put("plateNumber", order.getAttach());
            map.put("endTime", carPrivateInfo.getRenewExpirationTime());
            mnsMessage.setType(CarConstant.CAR_MSG_TYPE_MONTHLY_POSTPONED);
            mnsMessage.setContent(map);
            mnsMessage.setTimeout(1296000);
            mnsService.producer(order.getAttach2(), JSON.toJSONString(mnsMessage));
        } else if (order.getOrderType().equals(ORDER_CAR_LANE)) {
            CarPrivateInfo carPrivateInfo = JSON.parseObject(order.getDetail(), CarPrivateInfo.class);
            CarMNSMessage carLanePay = new CarMNSMessage();
            Map<String, Object> map = new HashMap<>();
            map.put("laneCode", carPrivateInfo.getLaneCode());
            carLanePay.setType(CarConstant.CAR_MSG_TYPE_CAR_LANE_PAY_SUCCESS);
            carLanePay.setContent(map);
            carLanePay.setTimeout(5);
            LogHelper.d("---------->     停车场编号: " + order.getAttach2() + "     车牌号: " + order.getAttach());
            HashOperations hashOperations = stringTemplate.opsForHash();
            hashOperations.put(CarConstant.REDIS_HEAD_PARKING_LOT + order.getAttach2(), order.getAttach(), "1");
            mnsService.producer(order.getAttach2(), JSON.toJSONString(carLanePay));
        } else if (order.getOrderType().equals(ORDER_CAR_ORDERED)) {
            CarMNSMessage carMNSMessage = new CarMNSMessage();
            Map<String, Object> map = new HashMap<>();
            map.put("plateNumber", order.getAttach());
            map.put("allowTime", 30);
            carMNSMessage.setType(CarConstant.CAR_MSG_TYPE_PREMATURE_PAYMENT_SUCCESS);
            carMNSMessage.setContent(map);
            carMNSMessage.setTimeout(60);
            LogHelper.d("---------->     PREMATURE_PAYMENT_SUCCESS:" + JSON.toJSONString(carMNSMessage));
            LogHelper.d("---------->     停车场编号: " + order.getAttach2() + "     车牌号: " + order.getAttach());
            HashOperations hashOperations = stringTemplate.opsForHash();
            hashOperations.put(CarConstant.REDIS_HEAD_PARKING_LOT + order.getAttach2(), order.getAttach(), "1");
            mnsService.producer(order.getAttach2(), JSON.toJSONString(carMNSMessage));
        }
    }

    @Override
    public boolean preCheck(Order order) {
        LogHelper.d("--------------------> sssss " + order.toString());

        switch (order.getOrderType()) {
            case ORDER_CAR_MONTH: {
                CarPrivateInfo carPrivateInfo = JSON.parseObject(order.getDetail(), CarPrivateInfo.class);
                return !StringUtils.isEmpty(order.getOrderType()) &&
                        !StringUtils.isEmpty(order.getCommCode()) &&
                        !StringUtils.isEmpty(order.getAttach()) &&
                        !StringUtils.isEmpty(order.getAttach2()) &&
                        !StringUtils.isEmpty(order.getBody()) &&
                        !StringUtils.isEmpty(carPrivateInfo.getRenewExpirationTime());
            }
            case ORDER_CAR_LANE: {
                if (StringUtils.isEmpty(order.getCommCode())) {
                    order.setCommCode(getCommCodeByParkId(order.getAttach2()));
                }
                CarPrivateInfo carPrivateInfo = JSON.parseObject(order.getDetail(), CarPrivateInfo.class);
                return !StringUtils.isEmpty(order.getCommCode()) &&
                        !StringUtils.isEmpty(order.getAttach2()) &&
                        !StringUtils.isEmpty(order.getAttach()) &&
                        !StringUtils.isEmpty(carPrivateInfo.getLaneCode());
            }
            case ORDER_CAR_ORDERED: {
                if (StringUtils.isEmpty(order.getCommCode())) {
                    order.setCommCode(getCommCodeByParkId(order.getAttach2()));
                }
                return !StringUtils.isEmpty(order.getCommCode()) &&
                        !StringUtils.isEmpty(order.getAttach2()) &&
                        !StringUtils.isEmpty(order.getAttach());
            }
            default: {
                if (StringUtils.isEmpty(order.getCommCode())) {
                    order.setCommCode(getCommCodeByParkId(order.getAttach2()));
                }
                return !StringUtils.isEmpty(order.getCommCode()) &&
                        !StringUtils.isEmpty(order.getAttach2()) &&
                        !StringUtils.isEmpty(order.getAttach());
            }
        }
    }

    @Override
    @PostConstruct
    public void registerModule() {
        orderService.registerModule(this);
    }

    @Override
    public PayCustomerSecret findCustomerSecret(Order order) throws Exception {
        ParkingLot parkingLot = parkingLotService.queryParkingLotInfo(order.getAttach2());
        return payCustService.findCustSecretByPayType(parkingLot.getPayCustomerId(), order.getPayType());
    }

    @Override
    public void setCustomerId(String id, Long customId) {
        ParkingLot parkingLot = parkingLotService.queryParkingLotInfo(id);
        parkingLot.setPayCustomerId(customId);
        parkingLotService.saveParkingLot(parkingLot);
    }

    @Override
    public Map getDetailInfoForOrder(Order order) {
        Map map = new HashMap();
        map.put("车牌号", order.getAttach());
        map.put("停车场编号", order.getAttach2());
        CarPrivateInfo carPrivateInfo = JSON.parseObject(order.getDetail(), CarPrivateInfo.class);
        if (carPrivateInfo != null)
            map.put("到期时间", carPrivateInfo.getRenewExpirationTime());
        return map;
    }

    //根据停车场ID获取小区编号
    private String getCommCodeByParkId(String parkId) {
        ParkingLot parkingLot = parkingLotService.queryParkingLotInfo(parkId);
        return parkingLot != null ? parkingLot.getCommCode() : null;
    }

    @Override
    public List<PayModuleInfo> getPayModuleInfo(String orderType, String commCode) {
        List list = new ArrayList();
        List<ParkingLot> parkList = parkingLotService.queryParkingLostByWhere("where comm_code = '" + commCode + "'");
        if (parkList != null) {
            for (ParkingLot park : parkList) {
                PayModuleInfo payModuleInfo = new PayModuleInfo();
                payModuleInfo.setId(park.getParkId());
                payModuleInfo.setName(park.getParkName());
                payModuleInfo.setCustomId(park.getPayCustomerId());
                payModuleInfo.setOrderType(orderType);
                payModuleInfo.setOrderDesc(orderService.getModuleDesc(orderType));
                list.add(payModuleInfo);
            }
        }

        return list;
    }
}
